import React, { useEffect, useRef, useState } from "react";
import { parseStockDataList, StockData } from "./util";

function App() {
  // const [stockData, setStockData] = useState<StockData[]>([]);
  const [stockDataQueue, setStockDataQueue] = useState<StockData[]>([
    { name: "", currentPrice: "", profitLoss: "loading" },
  ]);
  const [currentIndex, setCurrentIndex] = useState(0); // 用于追踪当前显示的股票数据索引
  const ballRef = useRef<HTMLDivElement>(null);
  const [showCurrentPrice, setShowCurrentPrice] = useState(false);
  const handleMouseEnter = () => {
    setShowCurrentPrice(true); // 显示当前价格
  };

  const handleMouseLeave = () => {
    setShowCurrentPrice(false); // 隐藏当前价格
  };

  useEffect(() => {
    const callback = () => {
      const myStocks = window.Main.getStocks();
      const stockCodes = myStocks.join(","); // 将股票代码数组转换为URL参数格式
      const url = `http://stock-data.plusii.com/data/?s=${stockCodes}&t=${Date.now()}`;
      fetch(url)
        .then((response) => response.text())
        .then((data) => {
          // alert(data);
          const myStockData = parseStockDataList(data);
          setStockDataQueue(myStockData);
        })
        .catch((error) => {
          console.error("Error fetching stock data:", error);
        });
    };
    callback();
    const intervalId = setInterval(callback, 5000); // 每5000毫秒（5秒）请求一次
    return () => clearInterval(intervalId);
  }, []);

  useEffect(() => {
    const ticker = setInterval(() => {
      if (stockDataQueue.length) {
        // 循环显示股票数据
        const nextIndex = (currentIndex + 1) % stockDataQueue.length;
        setCurrentIndex(nextIndex);
      }
    }, 2000); // 每3000毫秒（3秒）更新一次数据展示

    return () => clearInterval(ticker);
  }, [stockDataQueue]);

  useEffect(() => {
    const ballElement = ballRef.current;

    const handleClick = () => {
      // 这里写点击悬浮窗后想要执行的逻辑
      window.Main.hideMainWindow();
      // 例如，隐藏主窗口
    };

    if (ballElement) {
      ballElement.addEventListener("click", handleClick);
    }

    // Cleanup function to remove the event listener
    return () => {
      if (ballElement) {
        ballElement.removeEventListener("click", handleClick);
      }
    };
  }, []);
  return (
    <div
      className="stock-ticker"
      ref={ballRef}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      <div className="stock-info">
        <div className="stock-name text-center">
          {stockDataQueue[currentIndex].name}
        </div>
        {showCurrentPrice && (
          <div
            className={`text-center profit-${
              stockDataQueue[currentIndex].profitLoss.includes("-")
                ? "loss"
                : "gain"
            }`}
          >
            ￥{stockDataQueue[currentIndex].currentPrice}
          </div>
        )}
        {!showCurrentPrice && (
          <div
            className={`text-center profit-${
              stockDataQueue[currentIndex].profitLoss.includes("-")
                ? "loss"
                : "gain"
            }`}
          >
            {stockDataQueue[currentIndex].profitLoss}
          </div>
        )}
      </div>
    </div>
  );
}

export default App;
